package dom;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class TestDomParserPrint {

    public static void main(String[] args) {


        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        try {
            //获得解析器
            DocumentBuilder parser=factory.newDocumentBuilder();


            //解析，将xml解析完成，文件已经全部读取完毕，在内存中已经有一个树形结构
            Document document=parser.parse(TestDomParser.class
                    .getClassLoader()
                    .getResourceAsStream("students.xml"));





            Element root=document.getDocumentElement();

            print(root);



        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }


    public static void print(Element root){

        System.out.print("<"+root.getTagName()+" ");

        NamedNodeMap map=root.getAttributes();

        if(map!=null){
            for (int i = 0; i < map.getLength(); i++) {
                Attr attr= (Attr) map.item(i);
                System.out.print(attr.getName()+"="+attr.getValue()+" ");
            }
        }

        System.out.print(">");


        NodeList nodeList=root.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node=nodeList.item(i);
            short nodeType=node.getNodeType();

            if(nodeType==Node.TEXT_NODE){
                System.out.print(node.getNodeValue());
            }

            if(nodeType==Node.ELEMENT_NODE){
                Element element= (Element) node;
                print(element);
            }

        }

        System.out.print("</"+root.getTagName()+">");


    }
}
